// ReviewServiceImpl.java
package cn.tedu.apps_system.service.impl;

import cn.tedu.apps_system.base.response.ResultCode;
import cn.tedu.apps_system.exception.BusinessException;
import cn.tedu.apps_system.mapper.ReviewMapper;
import cn.tedu.apps_system.pojo.dto.ReviewReplyDTO;
import cn.tedu.apps_system.pojo.entity.Review;
import cn.tedu.apps_system.pojo.vo.ReviewVO;
import cn.tedu.apps_system.service.ReviewService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReviewServiceImpl implements ReviewService {

    @Autowired
    private ReviewMapper reviewMapper;

    @Override
    public void reply(ReviewReplyDTO reviewReplyDTO) {
        Review review = reviewMapper.selectById(reviewReplyDTO.getId());
        if (review == null) {
            throw new BusinessException(ResultCode.REVIEW_NOT_EXIST);
        }

        // 检查商家是否匹配
        if (!review.getMerchantId().equals(reviewReplyDTO.getMerchantId())) {
            throw new BusinessException(ResultCode.REVIEW_MERCHANT_MISMATCH);
        }

        review.setReply(reviewReplyDTO.getReply());
        review.setReplyTime(new Date());

        reviewMapper.updateReply(review);
    }

    @Override
    public List<ReviewVO> listByProductId(Long productId) {
        List<Review> reviews = reviewMapper.selectByProductId(productId);
        return reviews.stream().map(review -> {
            ReviewVO reviewVO = new ReviewVO();
            BeanUtils.copyProperties(review, reviewVO);
            return reviewVO;
        }).collect(Collectors.toList());
    }

    @Override
    public List<ReviewVO> listByMerchantId(Long merchantId) {
        List<Review> reviews = reviewMapper.selectByMerchantId(merchantId);
        return reviews.stream().map(review -> {
            ReviewVO reviewVO = new ReviewVO();
            BeanUtils.copyProperties(review, reviewVO);
            return reviewVO;
        }).collect(Collectors.toList());
    }
}